var mysql=require("mysql");  
var crypto = require('./crypto');

var pool = null;

function nop(a,b,c,d,e,f,g){

}
exports.query = query;
function query(sql,callback){
    // console.log(sql); 
    pool.getConnection(function(err,conn){  
        if(err){  
            callback(err,null,null);  
        }else{  
            conn.query(sql,function(qerr,vals,fields){  
                //释放连接  
                conn.release();  
                //事件驱动回调  
                callback(qerr,vals,fields);  
            });  
        }  
    });  
};

exports.init = function(config){
    pool = mysql.createPool({  
        host: config.HOST,
        user: config.USER,
        password: config.PSWD,
        database: config.DB,
        port: config.PORT,
    });
};

exports.is_account_exist = function(account,callback){
    callback = callback == null? nop:callback;
    if(account == null){
        callback(false);
        return;
    }

    var sql = "SELECT * FROM t_accounts WHERE account = '{0}'";
    sql = sql.format(account);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(true);
            }
            else{
                callback(false);
            }
        }
    });
};

//废弃
exports.create_account = function(account,password,callback){
    callback = callback == null? nop:callback;
    if(account == null || password == null){
        callback(false);
        return;
    }
    var psw = crypto.md5(password);
    var sql = "INSERT INTO t_accounts(account,password) VALUES('" + account + "','" + psw + "')";
    query(sql, function(err, rows, fields) {
        console.log(err);
            console.log(rows);
        if (err) {
            if(err.code == 'ER_DUP_ENTRY'){
                callback(false);
                return;         
            }
            callback(false);
            throw err;
        }
        else{
            callback(true);            
        }
    });
};

exports.get_account_info = function(account,password,callback){
    callback = callback == null? nop:callback;
    if(account == null){
        callback(null);
        return;
    }  

    var sql = "SELECT * FROM t_accounts WHERE account = '{0}'";
    sql = sql.format(account);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(null);
            throw err;
        }
        
        if(rows.length == 0){
            callback(null);
            return;
        }
        
        if(password != null){
            var psw = crypto.md5(password);
            if(rows[0].password == psw){
                callback(null);
                return;
            }    
        }

        callback(rows[0]);
    }); 
};


exports.is_unionid_exist = function(unionid,callback){
    callback = callback == null? nop:callback;
    if(unionid == null){
        callback(false);
        return;
    }

    var sql = "SELECT account,userid FROM t_users WHERE unionid = '{0}'";
	sql = sql.format(unionid);
    query(sql, function(err, rows, fields) {
        if (err) {
            throw err;
        }

        if(rows.length == 0){
            callback(false);
            return;
        }else{
            callback(rows[0]);
        }

    }); 
}
exports.is_user_exist = function(account,callback){
    callback = callback == null? nop:callback;
    if(account == null){
        callback(false);
        return;
    }

    var sql = "SELECT userid FROM t_users WHERE account = '{0}'";
    sql = sql.format(account);
    query(sql, function(err, rows, fields) {
        if (err) {
            throw err;
        }

        if(rows.length == 0){
            callback(false);
            return;
        }

        callback(true);
    });  
}


exports.get_user_data = function(account,callback){
    callback = callback == null? nop:callback;
    if(account == null){
        callback(null);
        return;
    }

    var sql = "SELECT userid,account,name,lv,exp,coins,gems,roomid,dealerid,game_amount,headimg,mtime,mobile,sum_yongjin,can_yongjin FROM t_users WHERE account = '{0}'";
    sql = sql.format(account);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(null);
            throw err;
        }

        if(rows.length == 0){
            callback(null);
            return;
        }
        rows[0].name = crypto.fromBase64(rows[0].name);
        callback(rows[0]);
    });
};

exports.get_user_data_by_userid = function(userid,callback){
    callback = callback == null? nop:callback;
    if( !(userid > 0) ){
        callback(null);
        return;
    }

    var sql = "SELECT userid,mobile,real_telphone,name FROM t_users WHERE userid ="+userid;
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(null);
            throw err;
        }

        if(rows.length == 0){
            callback(null);
            return;
        }
        rows[0].name = crypto.fromBase64(rows[0].name);
        callback(rows[0]);
    });
};

exports.get_user_data_by_userid1 = function(account,callback){
    var sql = "SELECT userid,account,name,lv,exp,coins,gems,roomid,dealerid,game_amount,headimg,mobile,clubsID,user_dealerid FROM t_users WHERE account = '"+account+"'";
    console.log(sql);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(null);
            throw err;
        }

        if(rows.length == 0){
            callback(null);
            return;
        }
        rows[0].name = crypto.fromBase64(rows[0].name);
        callback(rows[0]);
    });
};

/**增加玩家房卡 */
exports.add_user_gems = function(userid,gems,callback){
    callback = callback == null? nop:callback;
    if(userid == null){
        callback(false);
        return;
    }
    
    var sql = "UPDATE t_users SET gems = gems +{0} WHERE userid = '{1}'";
    sql = sql.format(gems, userid);
    // console.log(sql);
    query(sql,function(err,rows,fields){
        if(err){
            console.log(err);
            callback(false);
            return;
        }
        else{
            callback(rows.affectedRows > 0);
            return; 
        } 
    });
};

exports.add_user_gems1 = function(account,gems,callback){
    callback = callback == null? nop:callback;
    if(account == null){
        callback(false);
        return;
    }
    
    var sql = "UPDATE t_users SET gems = gems +"+gems+" WHERE account = '"+account+"'";
    // sql = sql.format(gems, account);
    // console.log(sql);
    query(sql,function(err,rows,fields){
        if(err){
            console.log(err);
            callback(false);
            return;
        }
        else{
            callback(rows.affectedRows > 0);
            return; 
        } 
    });
};

exports.add_gems_log = function(data, callback){
    callback = callback == null? nop:callback;
    if(data != null){
        var nowtime = parseInt(Date.parse(new Date())/1000);
        var sql = "insert into t_gems_log (num, total, type, userid, extra,mtime) values ('{0}', '{1}', '{2}', '{3}', '{4}','{5}')";
        sql = sql.format(data.num, data.total, data.type, data.userid,data.roomid,nowtime);
        query(sql,function(err,rows,fields){
            if(err){
                if(err.code == 'ER_DUP_ENTRY'){
                    callback(false);
                    return;         
                }
                callback(false);
                throw err;
            }
            else{
                callback(true);
            }
        });
    }
}

exports.get_gems = function(userid,callback){
    callback = callback == null? nop:callback;
    if(userid == null || isNaN(userid)){
        callback(null);
        return;
    }

    var sql = "SELECT gems FROM t_users WHERE userid = '{0}'";
    sql = sql.format(userid);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(null);
            throw err;
        }

        if(rows.length == 0){
            callback(null);
            return;
        }

        callback(rows[0]);
    });
}; 

exports.get_user_history = function(userId,callback){
    callback = callback == null? nop:callback;
    if(userId == null){
        callback(null);
        return;
    }

    var sql = "SELECT history FROM t_users WHERE userid = '{0}'";
    sql = sql.format(userId);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(null);
            throw err;
        }

        if(rows.length == 0){
            callback(null);
            return;
        }
        var history = rows[0].history;
        if(history == null || history == ""){
            callback(null);    
        }
        else{
            // console.log("-------history.length------:"+history.length);
            history = JSON.parse(history);
            callback(history);
        }        
    });
};

exports.clear_user_roomid = function(userId, callback){
    callback = callback == null? nop:callback;
    if(!isNaN(userId) && userId > 0){
        var sql = "UPDATE t_users SET roomid = null WHERE userid = '{0}'";
        sql = sql.format(userId);
        query(sql, function(err, rows, fields) {
            if (err) {
                callback(false);
                throw err;
            }

            if(rows.length == 0){
                callback(false);
                return;
            }

            callback(true);
        });
    }
}

exports.update_user_history = function(userId,history,callback){
    callback = callback == null? nop:callback;
    if(userId == null || history == null){
        callback(false);
        return;
    }

    history = JSON.stringify(history);
    var sql = "UPDATE t_users SET roomid = null, history = '{0}' WHERE userid = '{1}'";
    sql = sql.format(history, userId);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
        }

        if(rows.length == 0){
            callback(false);
            return;
        }

        callback(true);
    });
};

exports.get_games_of_room = function(room_uuid,callback){
    callback = callback == null? nop:callback;
    if(room_uuid == null){
        callback(null);
        return;
    }

    var sql = "SELECT game_index,create_time,result FROM t_games_archive WHERE room_uuid = '{0}'";
    //console.log(sql);
    sql = sql.format(room_uuid);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(null);
            throw err;
        }

        if(rows.length == 0){
            callback(null);
            return;
        }

        callback(rows);
    });
};

//查询对应的充钻表

exports.get_shop_item = function(callback){
	callback = callback == null? nop:callback;
    var sql = "select * from t_shopitem";
    // console.log(sql);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
           if(rows.length > 0){
        	  // rows = JSON.parse(rows)
        	   callback(rows);
           }
        }
    });
}


//根据roomid 查询对应的游戏回放记录列表
exports.get_rooms_rows_bak = function(roomid,userid,isHistory,callback){
	callback = callback == null ? nop:callback;
	if(roomid == null){
		callback(null);
		return;
	}
	if(userid == null){
		callback(null);
		return;
	}
	// console.log(roomid);
	// console.log(isHistory);
	 if(isHistory){
		 var sql = "select a.creator, b.history from t_rooms_history as a left join t_users as b on a.creator = b.userid where a.roomid = '{0}'";
		//  console.log("====sql:=="+sql);  
	 }else{
		 var sql = "select a.creator, b.history from t_rooms as a left join t_users as b on a.creator = b.userid where a.id = '{0}'";;
	 }
	 sql = sql.format(roomid);
	 query(sql,function(err,rows,fields){
		 if(err){
			 callback(null);
			 throw err;
		 }
		 if(rows.length == 0){
	            callback(null);
	            return;
	        }
		 var history = rows[0].history;
        if(history == null || history == ""){
            callback(null);    
        }
        else{
            // console.log("-------history.length------:"+history.length);
            history = JSON.parse(history);
        //   console.log("-------history------:"+history);
            callback(history);
        }    
	 });

};

//根据roomid 查询对应的游戏回放记录列表
exports.get_rooms_rows = function(readuserid,callback){
	callback = callback == null ? nop:callback;
	if(readuserid == null){
		callback(null);
		return;
	}
	
	 var sql = "SELECT history FROM t_users WHERE userid = '{0}'"
	 sql = sql.format(readuserid);
	 query(sql,function(err,rows,fields){
		 if(err){
			 callback(null);
			 throw err;
		 }
		 if(rows.length == 0){
	            callback(null);
	            return;
	        }
		 var history = rows[0].history;
        if(history == null || history == ""){
            callback(null);    
        }
        else{
            // console.log("-------history.length------:"+history.length);
            history = JSON.parse(history);
        //   console.log("-------history------:"+history);
            callback(history);
        }    
	 });

};

//获取最新的玩家房间记录（roomid有重复）
exports.get_one_roomhistory = function(roomid,userid,isHistory,callback){
    callback = callback == null? nop:callback;
    if(roomid == null || userid == null){
        callback(null);
        return;
    }
    if(isHistory){
    	 var sql = "SELECT user_id0 as readuserid FROM t_rooms_history WHERE roomid = '{0}' order by create_time desc limit 1";
    }else{
    	 var sql = "SELECT user_id0 as readuserid FROM t_rooms WHERE id = '{0}' order by create_time desc limit 1";
    }
    sql = sql.format(roomid);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(null);
            throw err;
        }

        if(rows.length == 0){
            callback(null);
            return;
        }else{
        	callback(rows[0]['readuserid']);
        }
        
    });
}

exports.get_detail_of_game = function(room_uuid,index,callback){
    callback = callback == null? nop:callback;
    if(room_uuid == null || index == null){
        callback(null);
        return;
    }
    var sql = "SELECT base_info,action_records,result FROM t_games_archive WHERE room_uuid = '{0}' AND game_index = {1}";
    sql = sql.format(room_uuid, index);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(null);
            throw err;
        }

        if(rows.length == 0){
            callback(null);
            return;
        }
        callback(rows[0]);
    });
}

exports.create_user = function(account,name,coins,gems,sex,headimg,unionid,callback){
    callback = callback == null? nop:callback;
    if(account == null || account == undefined || name == null || coins==null || gems==null){
        callback(false);
        return;
    }
    if(headimg){
        headimg = '"' + headimg + '"';
    }
    else{
        headimg = 'null';
    }
    // console.log("-------create_user--------unionid:"+unionid);
    name = crypto.toBase64(name);
    var nowtime = parseInt(Date.parse(new Date())/1000);
    var sql = "INSERT INTO t_users(account,name,coins,gems,sex,headimg,unionid,mtime) VALUES('{0}','{1}',{2},{3},{4},{5},'{6}',{7})";
    sql = sql.format(account,name,coins,gems,sex,headimg,unionid,nowtime);
    // console.log(sql);
    query(sql, function(err, rows, fields) {
        if (err) {
            if(err.code == 'ER_DUP_ENTRY'){
                callback(false);
                return;         
            }
            throw err;
        }
        var insertId = rows.insertId;
        callback(true,insertId);
    });
};
exports.update_user_name = function(account, callback){
    var name = crypto.toBase64(account);
    var sql = "UPDATE t_users SET name='"+name+"'  WHERE account='"+account+"'";
    return query(sql, function(){
        callback(true);
    });
}
exports.update_user_info = function(unionid,account,name,headimg,sex,callback){
    callback = callback == null? nop:callback;
    if(unionid == null){
        callback(null);
        return;
    }
 
    if(headimg){
        headimg = '"' + headimg + '"';
    }
    else{
        headimg = 'null';
    }

    if(name == undefined || name == null){
        callback(null);
        return;
    }
    name = crypto.toBase64(name);
    var sql = "UPDATE t_users SET name='{0}',headimg={1},sex={2},account='{3}' WHERE unionid='{4}'";
    sql = sql.format(name,headimg,sex,account,unionid);
    // console.log(sql);
    query(sql, function(err, rows, fields) {
        if (err) {
            throw err;
        }
        callback(rows);
    });
};

exports.get_user_base_info = function(userid,callback){
    callback = callback == null? nop:callback;
    if(userid == null){
        callback(null);
        return;
    }
    var sql = "SELECT u.userid, u.name,u.sex,u.headimg,u.gems,u.dealerid,u.game_amount, u.mtime as register_time, h.house_name,u.mobile FROM t_users as u left join t_houses as h on (u.dealerid = h.chairman_id) WHERE u.userid={0}";
    sql = sql.format(userid);
    // console.log(sql);
    query(sql, function(err, rows, fields) {
        if (err) {
            throw err;
        }
        if(rows.length > 0 && rows[0] != undefined && rows[0] != null){
            rows[0].name = crypto.fromBase64(rows[0].name);
            callback(rows[0]);
        }else{
            callback(null);
        }
    });
};


//根据用户代理的id 查询对应的userid
exports.get_creattid_userid = function(create_id,callback){
    callback = callback == null? nop:callback;
    var sql = "SELECT user_name FROM xx_game_admin WHERE id = '{0}'";
    sql = sql.format(create_id);
    query(sql, function(err, rows, fields) {
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows[0]);
            }else{
                callback(null);
            }
        }
    });
};

//检测之前的用户优惠码是否是上级不是则将原来的更新成上级的
exports.update_dealer_charge = function(dealer_id,userid,callback){
    callback = callback == null? nop:callback;
    var sql = "UPDATE t_users SET dealerid ='{0}'  WHERE userid = '{1}'";
    sql = sql.format(dealer_id, userid);
    query(sql, function(err, rows, fields) {
        if(err){
            callback(false);
            throw err;
        }
        else{
            callback(rows.length > 0);
        }
    });
};


exports.is_room_exist = function(roomId,callback){
    callback = callback == null? nop:callback;
    var sql = "SELECT * FROM t_rooms WHERE id = '{0}'";
    sql = sql.format(roomId);
    query(sql, function(err, rows, fields) {
        if(err){
            callback(false);
            throw err;
        }
        else{
            callback(rows.length > 0);
        }
    });
};

exports.cost_gems = function(userid,cost,callback){
    callback = callback == null? nop:callback;
    var sql = "UPDATE t_users SET gems = gems -'{0}' WHERE userid = '{1}'";
    sql = sql.format(cost, userid);
    query(sql, function(err, rows, fields) {
        if(err){
            callback(false);
            throw err;
        }
        else{
            callback(rows.length > 0);
        }
    });
};

exports.cost_gems_log = function(data, callback){
    callback = callback == null? nop:callback;

    var sql = "insert into t_game_cost_log (num, gametype, subtype, mtime, ) values ()";
}

exports.set_room_id_of_user = function(userId,roomId,callback){
    callback = callback == null? nop:callback;
    if(roomId != null){
        var sql = "UPDATE t_users SET roomid = '{0}' WHERE userid = '{1}'";
        sql = sql.format(roomId, userId);
    }else{
        var sql = "UPDATE t_users SET roomid = null WHERE userid = '{0}'";
        sql = sql.format(userId);
    }
    query(sql, function(err, rows, fields) {
        if(err){
            console.log(err);
            callback(false);
            throw err;
        }
        else{
            callback(rows.length > 0);
        }
    });
};

exports.get_room_id_of_user = function(userId,callback){
    callback = callback == null? nop:callback;
    var sql = "SELECT roomid FROM t_users WHERE userid = '{0}'";
    sql = sql.format(userId);
    query(sql, function(err, rows, fields) {
        if(err){
            callback(null);
            throw err;
        }
        else{
            // console.log("=======DB get_room_id_of_user=======");
            // console.log(rows);
            if(rows.length > 0){
                callback(rows[0].roomid);
            }
            else{
                callback(null);
            }
        }
    });
};


exports.create_room = function(roomId,conf,ip,port,createType,creator,create_time,callback,isClubTable,club_id,club_name){
    callback = callback == null? nop:callback;
    var sql = "INSERT INTO t_rooms(uuid,id,base_info,ip,port,create_type,creator,create_time,isClubTable,club_id,club_name) \
                VALUES('{0}','{1}','{2}','{3}',{4},{5},{6},{7},{8},{9},'{10}')";
    var uuid = Date.now() + roomId;
    var baseInfo = JSON.stringify(conf);
    sql = sql.format(uuid,roomId,baseInfo,ip,port,createType,creator,create_time,isClubTable,club_id,club_name);
    // console.log(sql);
    query(sql,function(err,row,fields){
        if(err){
            if(err.code == 'ER_DUP_ENTRY'){
                callback(false);
                return;         
            }
            callback(null);
            throw err;
        }
        else{
            callback(uuid);
        }
    });
};

exports.get_room_uuid = function(roomId,callback){
    callback = callback == null? nop:callback;
    var sql = "SELECT uuid FROM t_rooms WHERE id = '{0}'";
    sql = sql.format(roomId);
    query(sql,function(err,rows,fields){
        if(err){
            callback(null);
            throw err;
        }
        else{
            callback(rows[0].uuid);
        }
    });
};

exports.update_seat_info = function(roomId,seatIndex,userId,icon,name,callback){
    callback = callback == null? nop:callback;
    var sql = "UPDATE t_rooms SET user_id{0} = {1},user_icon{0} = '{2}',user_name{0} = '{3}' WHERE id = '{4}'";
    if(name != "" || name != null){
        name = crypto.toBase64(name);
    }
    sql = sql.format(seatIndex,userId,icon,name,roomId);
    //console.log(sql);
    query(sql,function(err,row,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            callback(true);
        }
    });
}

exports.update_num_of_turns = function(roomId,numOfTurns,callback){
    callback = callback == null? nop:callback;
    var sql = 'UPDATE t_rooms SET num_of_turns = {0} WHERE id = "{1}"'
    sql = sql.format(numOfTurns,roomId);
    //console.log(sql);
    query(sql,function(err,row,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            callback(true);
        }
    });
};


exports.update_next_button = function(roomId,nextButton,callback){
    callback = callback == null? nop:callback;
    var sql = 'UPDATE t_rooms SET next_button = {0} WHERE id = "{1}"'
    sql = sql.format(nextButton,roomId);
    //console.log(sql);
    query(sql,function(err,row,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            callback(true);
        }
    });
};

exports.get_room_addr = function(roomId,callback){
    callback = callback == null? nop:callback;
    if(roomId == null){
        callback(false,null,null);
        return;
    }

    var sql = "SELECT ip,port FROM t_rooms WHERE id = '{0}'";
    sql = sql.format(roomId);
    query(sql, function(err, rows, fields) {
        if(err){
            callback(false,null,null);
            throw err;
        }
        if(rows.length > 0){
            callback(true,rows[0].ip,rows[0].port);
        }
        else{
            callback(false,null,null);
        }
    });
};

exports.get_room_data = function(roomId,callback){
    callback = callback == null? nop:callback;
    if(roomId == null){
        callback(null);
        return;
    }

    var sql = "SELECT * FROM t_rooms WHERE id = '{0}'";
    sql = sql.format(roomId);
    query(sql, function(err, rows, fields) {
        if(err){
            callback(null);
            throw err;
        }
        if(rows.length > 0){
            // console.log(rows[0]);
            if(rows[0].user_name0)
                rows[0].user_name0 = crypto.fromBase64(rows[0].user_name0);
            if(rows[0].user_name1)
                rows[0].user_name1 = crypto.fromBase64(rows[0].user_name1);
            if(rows[0].user_name2)
                rows[0].user_name2 = crypto.fromBase64(rows[0].user_name2);
            if(rows[0].user_name3)
                rows[0].user_name3 = crypto.fromBase64(rows[0].user_name3);
            callback(rows[0]);
        }
        else{
            callback(null);
        }
    });
};

exports.add_room_history = function(roomId, callback){
    callback = callback == null? nop:callback;
    if(roomId == null){
        callback(false);
        return;
    }

    var sql  = "insert into t_rooms_history (creator, uuid, roomid, base_info, create_type, create_time, num_of_turns, next_button,user_id0,user_icon0,user_name0,user_score0,user_id1,user_icon1,user_name1,user_score1,user_id2,user_icon2,user_name2,user_score2,user_id3,user_icon3,user_name3,user_score3,ip,mtime,isClubTable,club_id,club_name) select creator, uuid, id, base_info, create_type, create_time, num_of_turns, next_button,user_id0,user_icon0,user_name0,user_score0,user_id1,user_icon1,user_name1,user_score1,user_id2,user_icon2,user_name2,user_score2,user_id3,user_icon3,user_name3,user_score3,ip,unix_timestamp(),isClubTable,club_id,club_name from t_rooms where id = '{0}'";

    sql = sql.format(roomId);

    query(sql,function(err,rows,fields){
        if(err){
            if(err.code == 'ER_DUP_ENTRY'){
                callback(false);
                return;         
            }
            callback(false);
            throw err;
        }
        else{
            callback(true);
        }
    });
}

exports.delete_room = function(roomId,callback){
    callback = callback == null? nop:callback;
    if(roomId == null){
        callback(false);
    }
    var sql = "DELETE FROM t_rooms WHERE id = '{0}'";
    sql = sql.format(roomId);
    // console.log(sql);
    query(sql,function(err,rows,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            callback(true);
        }
    });
}

exports.create_game = function(room_uuid,index,base_info,callback){
    callback = callback == null? nop:callback;
    var sql = "INSERT INTO t_games(room_uuid,game_index,base_info,create_time) VALUES('{0}',{1},'{2}',unix_timestamp(now()))";
    sql = sql.format(room_uuid,index,base_info);
    console.log("======新建记录")
    console.log(sql);
    query(sql,function(err,rows,fields){
        if(err){
            if(err.code == 'ER_DUP_ENTRY'){
                callback(false);
                return;         
            }
            callback(null);
            throw err;
        }
        else{
            callback(rows.insertId);
        }
    });
};

exports.delete_games = function(room_uuid,callback){
    callback = callback == null? nop:callback;
    if(room_uuid == null){
        callback(false);
    }    
    var sql = "DELETE FROM t_games WHERE room_uuid = '{0}'";
    sql = sql.format(room_uuid);
    // console.log(sql);
    query(sql,function(err,rows,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            callback(true);
        }
    });
}

exports.archive_games = function(room_uuid,callback){
    callback = callback == null? nop:callback;
    if(room_uuid == null){
        callback(false);
    }
    var sql = "INSERT IGNORE INTO t_games_archive(SELECT * FROM t_games WHERE room_uuid = '{0}')";
    sql = sql.format(room_uuid);
    console.log("======备份数据回访====")
    console.log(room_uuid);
     console.log(sql);
    query(sql,function(err,rows,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            exports.delete_games(room_uuid,function(ret){
                callback(ret);
            });
        }
    });
}

exports.update_game_action_records = function(room_uuid,index,actions,callback){
    callback = callback == null? nop:callback;
    var sql = "UPDATE t_games SET action_records = '{0}' WHERE room_uuid = '{1}' AND game_index = '{2}'" ;
    sql = sql.format(actions, room_uuid, index);
    //console.log(sql);
    query(sql,function(err,rows,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            callback(true);
        }
    });
};

exports.update_game_result = function(room_uuid,index,result,callback){
    callback = callback == null? nop:callback;
    if(room_uuid == null || result){
        callback(false);
    }
    
    result = JSON.stringify(result);
    var sql = "UPDATE t_games SET result = '{0}' WHERE room_uuid = '{1}' AND game_index = '{2}'" ;
    sql = sql.format(result, room_uuid, index);
    //console.log(sql);
    query(sql,function(err,rows,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            callback(true);
        }
    });
};

exports.add_share_log = function(data, callback){
    callback = callback == null? nop:callback;

    if(data.userid > 0 && !isNaN(data.userid)){
        var nowtime = parseInt(Date.parse(new Date())/1000); 
        var sql = "insert into t_share_log (userid, account, ip, type, mtime) values ('{0}', '{1}', '{2}', '{3}', '{4}')";
        sql = sql.format(data.userid, data.account, data.ip,data.type, nowtime);
        query(sql,function(err,rows,fields){
            if(err){
                if(err.code == 'ER_DUP_ENTRY'){
                    callback(false);
                    return;         
                }
                callback(false);
                throw err;
            }
            else{
                callback(true);
            }
        });
    }

}
exports.is_first_share = function(userid, callback){
    callback = callback == null? nop:callback;

    if(userid > 0 && !isNaN(userid)){
        var todaytime = new Date(new Date().toLocaleDateString()).getTime(); 
        var todaytime_start = parseInt(todaytime/1000);
        var todaytime_end = todaytime_start + 86399;
        var sql = "select count(id) as count from t_share_log where userid = '{0}' and mtime >= '{1}' and mtime <= '{2}' and type = 1";
        
        sql = sql.format(userid, todaytime_start, todaytime_end);

        query(sql, function(err, rows, fields) {
            if(err){
                callback(false);
                //throw err;
            }
            else{
                if(rows.length > 0){
                    callback(rows[0]['count']);    
                }
                else{
                    callback(null);
                }
            }
        });

    }
};

exports.get_dealer_info = function (dealerid, callback){
    callback = callback == null? nop:callback;

    var sql = "select * from xx_game_admin where user_name = '{0}'";
    sql = sql.format(dealerid);
    query(sql, function(err, rows, fields) {
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows[0]);    
            }
            else{
                callback(null);
            }
        }
    });
}

exports.get_dealer_mobile = function(userid, callback){
    callback = callback == null? nop:callback;

    if(userid > 0){
        var sql = "select * from t_dealer_mobile where userid = '{0}'";
        sql = sql.format(userid);
        query(check_sql, function(err, rows, fields) {
            if(err){
                callback(false);
                throw err;
            }
            else if(rows.length > 0){
                callback(rows);
            }else{
                callback(false);
            }
        });
    }else{
        callback(false);
    }
}


//登记申请代理的手机
exports.add_dealer_mobile = function(data, callback){
    callback = callback == null? nop:callback;
    if(!(data.mobile > 0)){
        callback(null);
    }

    var nowtime = parseInt(Date.parse(new Date())/1000); 
    var sql = "insert into t_dealer_mobile (userid, account, mobile, ip, mtime) values ('{0}', '{1}', '{2}', '{3}', '{4}')";

    sql = sql.format(data.userid, data.account, data.mobile, data.ip, nowtime);

    query(sql, function(err, rows, fields) {
        if (err) {
            if(err.code == 'ER_DUP_ENTRY'){
                callback(false);
                return;         
            }
            callback(false);
            throw err;
        }
        else{
            callback(true);            
        }
    });
};

exports.check_bind_dealer_log = function(userid, callback){
    callback = callback == null? nop:callback;
    if(userid > 0 ){
        var check_sql = "select * from t_bind_dealer_log where userid = '{0}'";
        check_sql = check_sql.format(userid);
        query(check_sql, function(err, rows, fields) {
            if(err){
                callback(false);
                throw err;
            }
            else if(rows.length > 0){
                callback(true);
            }else{
                callback(false);
            }
        });
    }
}

exports.bind_dealer = function(dealerid, userid, callback){
    callback = callback == null? nop:callback;
    if(dealerid == null || userid == null){
        callback(null);
    }

    var check_sql = "select userid from t_users where userid = '{0}' and (dealerid is null or dealerid = '') ";
    check_sql = check_sql.format(userid);
    query(check_sql, function(err, rows, fields) {
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                //
                var update_sql = "update t_users set dealerid = '{0}' where userid = '{1}'";
                update_sql = update_sql.format(dealerid, userid);
                query(update_sql,function(update_err,update_rows,update_fields){
                    if(update_err){
                        console.log(update_err);
                        callback(false);
                        return;
                    }
                    else{
                        if(update_rows.affectedRows > 0){
                            callback(1);
                        }
                        return; 
                    } 
                });
            }
            else{
                callback(2);
                return;
                //已存在
            }
        }
    });
}

exports.add_playing_num = function(num, serverId, callback){
    callback = callback == null? nop:callback;

    if(num >= 0){
        var nowtime = parseInt(Date.parse(new Date())/1000); 
        var sql = "insert into t_playing_num_log (num, serverid, mtime) values ('{0}', '{1}', '{2}')";
        sql = sql.format(num, serverId, nowtime);
        query(sql, function(err, rows, fields) {
            if (err) {
                if(err.code == 'ER_DUP_ENTRY'){
                    callback(false);
                    return;         
                }
                callback(false);
                throw err;
            }
            else{
                callback(true);            
            }
        });
    }
}

exports.update_lastlogin = function(userid, callback){
    callback = callback == null? nop:callback;
    userid = parseInt(userid);
    if(!isNaN(userid) && userid>0){
        var nowtime = parseInt(Date.parse(new Date())/1000); 
        var sql = "update t_users set lastlogintime = '{0}' where userid = '{1}' ";
        sql = sql.format(nowtime, userid);
        query(sql,function(err,rows,fields){
            if(err){
                console.log(err);
                callback(false);
                return;
            }
            else{
                callback(rows.affectedRows > 0);
                return; 
            } 
        });
    }
}

exports.update_game_amount = function(userid, num, callback){
    callback = callback == null? nop:callback;

    if(userid != null && !isNaN(num)){
        var sql = "update t_users set game_amount = game_amount + {0} where userid = '{1}'";
        
        sql = sql.format(num, userid);

        query(sql,function(err,rows,fields){
            if(err){
                console.log(err);
                //callback(false);
                return;
            }
            else{
                //callback(rows.affectedRows > 0);
                return; 
            } 
        });
    }
}

//反馈记录
exports.add_feedback = function(data, callback){
    callback = callback == null? nop:callback;
    if(data.content != null){
        var nowtime = parseInt(Date.parse(new Date())/1000); 
        var sql = "insert into t_feedback (userid, account, content,telphone, mtime) values ('{0}', '{1}', '{2}' ,'{3}','{4}')";
        sql = sql.format(data.userid, data.account, data.content,data.telphone, nowtime);
        query(sql, function(err, rows, fields) {
            if (err) {
                if(err.code == 'ER_DUP_ENTRY'){
                    callback(false);
                    return;         
                }
                callback(false);
                throw err;
            }
            else{
                callback(true);            
            }
        });
    }

}


exports.add_login_log = function(data, callback){
    callback = callback == null? nop:callback;

    if(!isNaN(data.userid) && data.userid > 0){
        var nowtime = parseInt(Date.parse(new Date())/1000); 
        var sql = "insert into t_login_log (userid, account, login_time, ip, device) values ('{0}', '{1}', '{2}', '{3}', '{4}')";

        sql = sql.format(data.userid, data.account, nowtime, data.ip, data.device);

        query(sql, function(err, rows, fields) {
            if (err) {
                if(err.code == 'ER_DUP_ENTRY'){
                    callback(false);
                    return;         
                }
                callback(false);
                throw err;
            }
            else{
                callback(true);            
            }
        });
    }
}

exports.get_room_list = function(userid, isHistory, callback){
    callback = callback == null? nop:callback;
    userid = parseInt(userid);
    if(!isNaN(userid) && userid > 0){

        if(isHistory){
            var sql = "select creator,uuid,roomid as id,base_info,create_type,create_time,num_of_turns,next_button,user_id0,user_icon0,user_name0,user_score0,user_id1,user_icon1,user_name1,user_score1,user_id2,user_icon2,user_name2,user_score2,user_id3,user_icon3,user_name3,user_score3,ip,mtime from t_rooms_history where creator = '{0}' AND isClubTable = 0";
        }else{
            var sql = "select * from t_rooms where creator = '{0}' AND isClubTable = 0";
        }

        sql = sql.format(userid);

        query(sql, function(err, rows, fields) {
            if(err){
                callback(false);
                throw err;
            }
            else{
                if(rows.length > 0){
                    callback(rows);    
                }
                else{
                    callback(null);
                }
            }
        });
    }
}

exports.get_message = function(type,version,callback){
    callback = callback == null? nop:callback;
    
    var sql = "SELECT * FROM t_message WHERE type = '"+ type + "'";
    
    if(version == "null"){
        version = null;
    }
    
    if(version){
        version = "'" + version + "'";
        sql += " AND version != '" + version + "'";   
    }
     
    query(sql, function(err, rows, fields) {
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows[0]);    
            }
            else{
                callback(null);
            }
        }
    });
};

exports.get_item_info = function(itemId, callback){
    callback = callback == null? nop:callback;
    var itemSql = "";
    if(!isNaN(itemId) && itemId > 0){
        itemSql = " and id = '{0}'";
    }
    var sql = "select * from t_shopitem where 1 "+itemSql;
    if(!isNaN(itemId) && itemId > 0){
        sql = sql.format(itemId);
    }

    query(sql, function(err, rows, fields) {
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(itemId > 0 && rows.length > 0){
                callback(rows[0]);
            }
            else if(rows.length > 0){
                callback(rows);
            }else{
                callback(null);
            }
        }
    });
}

exports.update_order_payed = function(data, callback){
    callback = callback == null? nop:callback;

    if(data != null){
        var nowtime = parseInt(Date.parse(new Date())/1000);
        var sql = "update t_orders set state = '{0}', pay_time = '{1}', pay_type = '{2}' where trade_no = '{3}' and state = 1";

        sql = sql.format(data.state, nowtime, data.pay_type, data.trade_no);

        query(sql,function(err,rows,fields){
            if(err){
                console.log(err);
                callback(false);
                return;
            }
            else{
                callback(rows.affectedRows > 0);
                return; 
            } 
        });
    }
};

exports.get_order_info = function(tradeno, callback){
    callback = callback == null? nop:callback;

    if(tradeno != null){
        var sql = "select * from t_orders where trade_no = '{0}'";
        sql = sql.format(tradeno);
        query(sql, function(err, rows, fields) {
            if (err) {
                callback(false);
                throw err;
            }
            else{
                if(rows.length > 0){
                    callback(rows[0]);
                }
                else{
                    callback(false);
                }
            }
        });
    }
};

exports.order_list = function(userid,tradeno, callback){
    callback = callback == null? nop:callback;
    var where = "";
    if(tradeno != null || tradeno != ''){
        where += " and trade_no = '"+tradeno+"'";
    }
    var nowtime = parseInt(Date.parse(new Date())/1000);
    var sql = "select userid,dealerid,trade_no, body, total_amount, mtime, expire_time, pay_time, state from t_orders where userid = '{0}' and state = 2";//已付款

    sql = sql.format(userid);

    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows);
            }
            else{
                callback(false);
            }
        }
    });
}

exports.new_order = function(data, callback){
    callback = callback == null? nop:callback;

    if(data != null){
        var sql = "insert into t_orders (userid, dealerid, trade_no, device_type, game_type, attach,body,total_amount,ip,mtime,expire_time,state,user_dealerid) values ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}','{8}','{9}','{10}','{11}','{12}')";

        sql = sql.format(data.userid, data.dealerid, data.trade_no, data.device_type, data.game_type,data.attach, data.body, data.total_amount, data.ip, data.mtime, data.expire_time, data.state,data.user_dealerid);

        query(sql, function(err, rows, fields) {
            if (err) {
                if(err.code == 'ER_DUP_ENTRY'){
                    callback(false);
                    return;         
                }
                callback(false);
                throw err;
            }
            else{
                callback(true);            
            }
        });
    }
}

exports.get_three_dealer = function(userid, callback){
    callback = callback == null? nop:callback;

    if(!isNaN(userid) && userid > 0){
        var sql = "SELECT a.userid, b.id AS dealerid1, b.create_user_id AS dealerid2, c.create_user_id AS dealerid3 FROM ( SELECT dealerid, userid FROM t_users WHERE userid = '{0}' ) AS a LEFT JOIN ( SELECT id, create_user_id, user_name, area FROM xx_game_admin ) AS b ON (a.dealerid = b.user_name) LEFT JOIN ( SELECT id, create_user_id, user_name FROM xx_game_admin ) AS c ON (b.create_user_id = c.id)";
        sql = sql.format(userid);
        query(sql, function(err, rows, fields) {
            if (err) {
                callback(false);
                throw err;
            }
            else{
                if(rows.length > 0){
                    callback(rows[0]);
                }
                else{
                    callback(false);
                }
            }
        });

    }
}

exports.add_brokerage_log = function(data, callback){
    callback = callback == null? nop:callback;

    var nowtime = parseInt(Date.parse(new Date())/1000);
    var sql = "insert into t_brokerage_log (trade_no, player_id, dealer_id, level_id, brokerage_amount, order_amount, mtime, state) values ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '1')";
    sql = sql.format(data.trade_no,data.player_id,data.dealer_id,data.level_id,data.brokerage_amount,data.order_amount,nowtime);
    query(sql, function(err, rows, fields) {
        if (err) {
            if(err.code == 'ER_DUP_ENTRY'){
                callback(false);
                return;         
            }
            callback(false);
            throw err;
        }
        else{
            callback(true);            
        }
    });
}

exports.update_dealer_yongji = function(dealerid, amount,callback){
    callback = callback == null? nop:callback;

    if(!isNaN(dealerid) && !isNaN(amount)){
        var sql = "update xx_game_admin set yongjin = yongjin + '{0}' where user_name = '{1}'";
        sql = sql.format(amount,dealerid);
        query(sql,function(err,rows,fields){
            if(err){
                console.log(err);
                callback(false);
                return;
            }
            else{
                callback(rows.affectedRows > 0);
                return; 
            } 
        });
    }

}


exports.update_dealer_sum_yongji = function(dealerid, amount,callback){
    callback = callback == null? nop:callback;

    if(!isNaN(dealerid) && !isNaN(amount)){
        var sql = "update xx_game_admin set sum_yongjin = sum_yongjin + '{0}' where id = '{1}'";
        sql = sql.format(amount,dealerid);  
        query(sql,function(err,rows,fields){
            if(err){
                console.log(err);
                callback(false);
                return;
            }
            else{
                callback(rows.affectedRows > 0);
                return; 
            } 
        });
    }

}

exports.add_bind_dealer_log = function(dealerid, userid, ip, callback){
    callback = callback == null? nop:callback;

    if(!isNaN(dealerid) && !isNaN(userid)){
        var nowtime = parseInt(Date.parse(new Date())/1000);
        var sql = "insert into t_bind_dealer_log (userid, dealerid, ip, mtime) values ('{0}','{1}','{2}','{3}')";
        sql = sql.format(userid,dealerid,ip,nowtime);
        query(sql, function(err, rows, fields) {
            if (err) {
                if(err.code == 'ER_DUP_ENTRY'){
                    callback(false);
                    return;         
                }
                callback(false);
                throw err;
            }
            else{
                callback(true);            
            }
        });
    }
}

//服务器间http请求日志
exports.add_server_req_log = function(data, callback){
    callback = callback == null? nop:callback;

    var nowtime = parseInt(Date.parse(new Date())/1000);
    var sql = "insert into t_server_request_log (serverip, serverport, url, reqdata, userid, mtime) values ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}')";
    sql = sql.format(data.serverip,data.serverport,data.url,data.reqdata,data.userid,nowtime);

    query(sql, function(err, rows, fields) {
        if (err) {
            if(err.code == 'ER_DUP_ENTRY'){
                callback(false);
                return;         
            }
            callback(false);
            throw err;
        }
        else{
            callback(true);            
        }
    });    

}

//查询该用户是否有经纬度记录
exports.get_users_latlon = function(userid,callback){
    callback = callback == null? nop:callback;
    var sql = "SELECT userid FROM t_users_latlon WHERE userid = '{0}'";
    sql = sql.format(userId);
    query(sql, function(err, rows, fields) {
        if(err){
            callback(null);
            throw err;
        }
        else{
            // console.log("=======DB get_room_id_of_user=======");
            // console.log(rows);
            if(rows.length > 0){
                callback(rows[0].userid);
            }
            else{
                callback(null);
            }
        }
    });
}
//更新有经纬度记录
exports.update_users_latlon = function(userid,lat,lon,callback){
    callback = callback == null? nop:callback;

    if(!isNaN(userid)){
        var sql = "update t_users set lat = '{1}',lon = '{2}' where userid = '{0}'";
        sql = sql.format(userid,lat,lon);  
        query(sql,function(err,rows,fields){
            if(err){
                console.log(err);
                callback(false);
                return;
            }
            else{
                callback(rows.affectedRows > 0);
                return; 
            } 
        });
    }

}

//插入用户经纬度数据
exports.insert_users_latlon = function(userid,lat,lon,callback){
    callback = callback == null? nop:callback;
    if(userid == null){
        callback(null);
    }

    var check_sql = "SELECT * FROM t_users_latlon WHERE userid = '{0}'";
    check_sql = check_sql.format(userid);
    query(check_sql, function(err, rows, fields) {
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
    	       var update_sql = "update t_users_latlon set lat = '{1}',lon = '{2}' where userid = '{0}'";
               update_sql = update_sql.format(userid,lat,lon);
            //    console.log(update_sql);
               query(update_sql,function(update_err,update_rows,update_fields){
               if(update_err){
                   console.log(update_err);
                   callback(false);
                   return;
               }
               else{
                   if(update_rows.affectedRows > 0){
                       callback(true);
                   }
                   return; 
                   } 
               });
            	callback(true);
            	return;
            }
            else{
                var nowtime = parseInt(Date.parse(new Date())/1000);
                var insert_sql = "INSERT INTO t_users_latlon(userid,lat,lon,create_time) VALUES('"+userid+"','"+lat+"','"+lon+"','"+nowtime+"')";
            	//var insert_sql = "INSERT INTO t_users_latlon(userid,lat,lon,create_time) VALUES('{0}','{1}','{2}','{3}')";
            	//insert_sql = insert_sql.format(userid,lat,lon,nowtime);
            	// console.log(insert_sql);
            	query(insert_sql,function(insert_err,insert_rows,insert_fields){
                    if(insert_err){
                        console.log(insert_err);
                        callback(false);
                        return;
                    }
                    else{
                        callback(true);
                        return; 
                    } 
                });
            }
        }
    });
}



exports.get_other_plays = function(userId,data,callback){
	callback = callback == null? nop:callback;
	// console.log("===data.play=="+data.play);
	var play =  JSON.stringify(data.play);
	var plays = play.replace('[',"");
	var plays = plays.replace(']',"");
	// console.log("===plays=="+plays);
    var sql = "select * from t_users_latlon where userid in ("+plays+")";
        //sql = sql.format(data.play);  
        // console.log(sql);
        query(sql,function(err,rows,fields){
            if(err){
                console.log(err);
                callback(false);
                return;
            }
            else{
            	//rows = JSON.parse(rows);
                callback(rows);
                return; 
            } 
        });
}

//获取目标的经纬度数据
exports.get_benren_data = function(userId,callback){
	callback = callback == null? nop:callback;
    if(userId == null){
       callback(null);
    }
    var sql = "select * from t_users_latlon where userid  = '{0}'";
    sql = sql.format(userId);  
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
           console.log("benrendatadb==="+rows[0]);
           callback(rows[0]);
           
        }
    });
}

//查询是否增加了钻石
exports.is_updatesourceexit = function(userid,callback){
    callback = callback == null? nop:callback;

    if(userid > 0 && !isNaN(userid)){
        var sql = "select count(id) as count from t_gems_log where userid = '{0}' and type = 'updatesource_add'";
        
        sql = sql.format(userid);

        query(sql, function(err, rows, fields) {
            if(err){
                callback(false);
                //throw err;
            }
            else{
                if(rows.length > 0){
                    callback(rows[0]['count']);    
                }
                else{
                    callback(null);
                }
            }
        });

    }
};

//查询对应的充钻表

exports.is_open_shopitemactive = function(callback){
	callback = callback == null? nop:callback;
    var sql = "select * from t_shopitem";
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
           if(rows.length > 0){
        	  // rows = JSON.parse(rows)
        	   callback(rows[2]);
           }
        }
    });
}

//俱乐部
exports.create_club = function(club_id,bossid,name,ip, port,callback){
    port = port+"";
    callback = callback == null? nop:callback;
    if (club_id == null){
        callback(null);
        return;
    }
    if(bossid == null || isNaN(bossid)){
        callback(null);
        return;
    }
	if(!name){
        callback(null);
        return;
    }
	 var nowtime = parseInt(Date.parse(new Date())/1000);
     var sql = "insert into t_clubs (club_id,bossid, name, create_time, ip, port) values ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}')";
     sql = sql.format(club_id,bossid,name,nowtime, ip, port);
	 query(sql, function(err, rows, fields) {
        if (err) {
            if(err.code == 'ER_DUP_ENTRY'){
                callback(false);
                return;         
            }
            throw err;
        }else{
            callback(true);
		}
        
    });
}

exports.get_club_all = function(callback){
    callback = callback == null? nop:callback;
    var sql = "SELECT * FROM t_clubs";
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            if(rows.length > 0){
                callback(rows);
            }else{
                callback(null);
            }
        }
    });
}

exports.get_club = function(club_id,callback){
    callback = callback == null? nop:callback;
    var sql = "SELECT * FROM t_clubs WHERE club_id = '{0}'";
    sql = sql.format(club_id);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(null);
            throw err;
            return;
        }
        else{
            if(rows.length > 0){
                callback(rows[0]);
            }else{
                callback(null);
            }
        }
    });
}

exports.get_club_info = function(club_id,callback){
    callback = callback == null? nop:callback;
    var sql = "SELECT * FROM t_clubs_info WHERE club_id = '{0}'";
    sql = sql.format(club_id);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            if(rows.length > 0){
                callback(rows);
            }else{
                callback(false);
            }
        }
    });
}

exports.agree_club_req = function(club_id,request_userid,callback){
    callback = callback == null? nop:callback;
    if(club_id == null && request_userid == null){
        callback(null);
    }
    var sql = "SELECT * FROM t_clubs_info WHERE club_id = '{0}' AND request_userid = '{1}'";
    sql = sql.format(club_id,request_userid);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            if(rows.length > 0){
                var sql = "UPDATE t_clubs_info SET request_userid = '', member_userid = '{1}' WHERE club_id = '{0}' AND request_userid = '{1}'";
                sql = sql.format(club_id,request_userid);
                query(sql,function(err, rows, fields){
                    if (err) {
                        callback(false);
                        throw err;
                        return;
                    }else{
                         callback(rows.affectedRows > 0);
                         return; 
                    }
                })
            }else{
                callback(false);
            }
        }
    });
}

exports.disagree_club_req = function(club_id,request_userid,callback){
    callback = callback == null? nop:callback;
    if(club_id == null && request_userid == null){
        callback(null);
    }
    var sql = "SELECT * FROM t_clubs_info WHERE club_id = '{0}' AND request_userid = '{1}'"; 
    sql = sql.format(club_id,request_userid);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            if(rows.length > 0){
                var delete_sql = "DELETE FROM t_clubs_info WHERE club_id = '{0}' AND request_userid = '{1}'";
                delete_sql = delete_sql.format(club_id,request_userid);
                query(sql,function(err, rows, fields){
                    if (err) {
                        callback(false);
                        throw err;
                        return;
                    }else{
                        callback(true);
                    }
                })
            }else{
                callback(false);
            }
        }
    });
}

exports.join_club = function(club_id,request_userid,callback){
    callback = callback == null? nop:callback;
    var sql = "INSERT INTO t_clubs_info(club_id,request_userid) VALUES ('"+club_id+ "','"+request_userid+ "')";
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            callback(true);
        }
    });
}

exports.delete_club_user = function(club_id,userId,callback){
    callback = callback == null? nop:callback;
    var sql = "DELETE FROM t_clubs_info WHERE member_userid = '{0}' AND club_id = '{1}'";
    sql = sql.format(userId,club_id);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            callback(true);
        }
    });
}

exports.delete_club_room = function(club_id,callback){
    callback = callback == null? nop:callback;
    var sql = "DELETE FROM t_rooms WHERE club_id = '{0}'";
    sql = sql.format(club_id);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            callback(true);
        }
    });
}

exports.delete_club_allusers = function(club_id,callback){
    callback = callback == null? nop:callback;
    var sql = "DELETE FROM t_clubs_info WHERE club_id = '{0}'";
    sql = sql.format(club_id);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            callback(true);
        }
    });
}


exports.delete_club = function(club_id,userId,callback){
    callback = callback == null? nop:callback;
    var sql = "DELETE FROM t_clubs WHERE club_id = '{0}' AND bossid = '{1}'";
    sql = sql.format(club_id,userId);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            callback(true);
        }
    });
}

exports.get_club_member = function(club_id,callback){
	 callback = callback == null? nop:callback;
	 var sql = "SELECT userid,clubsID from t_users where clubsID like '%{0}%'";
     sql = sql.format(club_id);
	  query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
			if(rows.length > 0){
				 callback(rows);
			}
           
        }
    });
}

exports.updateClubTablesId = function(club_id,tablesId,callback){
    callback = callback == null? nop:callback;
    var sql = "UPDATE t_clubs SET tablesid = '{1}' WHERE club_id = '{0}'";
    sql = sql.format(club_id,tablesId);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            callback(true);
            if(rows.length > 0){
            }else{
                // console.log('更新俱乐部ids没影响')
            }
           
        }
    });
}

exports.updateUserClubs = function(userId,clubsID,callback){
    callback = callback == null? nop:callback;
    var sql = "UPDATE t_users SET clubsID = '{1}' WHERE userid = '{0}'";
    sql = sql.format(userId,clubsID);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            if(rows.length > 0){
            }
            callback(true);
        }
    });
}

exports.updateClubConf = function(clubID,conf,callback){
    callback = callback == null? nop:callback;
    var sql = "UPDATE t_clubs SET club_conf = '{1}' WHERE club_id = '{0}'";
    sql = sql.format(clubID,conf);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            if(rows.length > 0){
            }
            callback(true);
           
        }
    });
}

//更改俱乐部名字
exports.updateClubName = function(clubID,name,callback){
	callback = callback == null? nop:callback;
    var sql = "UPDATE t_clubs SET name = '{1}' WHERE club_id = '{0}'";
    sql = sql.format(clubID,name);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
           callback(true);
        }
    });
}

exports.updateRoomBaseInfo = function(roomId,conf,callback){
    callback = callback == null? nop:callback;
    var sql = "UPDATE t_rooms SET base_info = '{1}' WHERE id = '{0}'";
    sql = sql.format(roomId,conf);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            if(rows.length > 0){
            }
            callback(true);
           
        }
    });
}


exports.get_game_info = function(id,callback){
    callback = callback == null? nop:callback;
    if(id == null){
        callback(false);
        return;
    }

    var sql = "SELECT * FROM t_game_info WHERE id = '{0}'";
	sql = sql.format(id);
    query(sql, function(err, rows, fields) {
        if (err) {
            throw err;
        }

        if(rows.length == 0){
            callback(false);
            return;
        }else{
            callback(rows[0]);
        }

    }); 
}

exports.update_setzongjushu = function(id,zongju,nowtime,callback){
    callback = callback == null? nop:callback;
    var sql = "UPDATE t_game_info SET jushu = '{1}',create_time = '{2}' WHERE id = '{0}'";
    sql = sql.format(id,zongju,nowtime);
    query(sql, function(err, rows, fields) {
        if (err) {
            callback(false);
            throw err;
            return;
        }
        else{
            if(rows.length > 0){
            }
            callback(true);
        }
    });
}

//红包领取列表
exports.get_hongbao_list = function (userid,hongbao_type,callback){
    callback = callback == null? nop:callback;

    var sql = "select id,amount,status,create_time from t_hongbao where userid = '{0}' and hongbao_type = '{1}'";
    sql = sql.format(userid,hongbao_type);
    query(sql, function(err, rows, fields) {
        // console.log(rows);
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows);    
            }
            else{
                callback(null);
            }
        }
    });
}

//活动显示图标
exports.get_control_show = function (userid,callback){
    callback = callback == null? nop:callback;
    if(userid == null){
        callback(false);
        return;
    }
    var sql = "select huodong_status,huodong_type from t_huodong_show  where huodong_top = 1";
    query(sql, function(err, rows, fields) {
        // console.log(rows);
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows);    
            }
            else{
                callback(null);
            }
        }
    });
}


//活动消息图标
exports.get_activemessage_show = function (userid,callback){
    callback = callback == null? nop:callback;
    if(userid == null){
        callback(false);
        return;
    }
    var sql = "select huodong_status,huodong_type from t_huodong_show";
    query(sql, function(err, rows, fields) {
        // console.log(rows);
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows);    
            }
            else{
                callback(null);
            }
        }
    });
}

//红包领取金额 type = 5
exports.get_hongbao_yaoqing = function (userid, callback){
    callback = callback == null? nop:callback;
    if(userid == null){
        callback(false);
        return;
    }
    var sql = "select count(id) as hongbaonum from t_hongbao where userid = '{0}' and hongbao_type = 5 and status = 2";
    sql = sql.format(userid);
    // console.log(sql);
    query(sql, function(err, rows, fields) {
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows[0]);    
            }
            else{
                callback(null);
            }
        }
    });
}

//邀请的总人数
exports.get_yaoqing_uernum  = function (userid, callback){
    callback = callback == null? nop:callback;
    if(userid == null){
        callback(false);
        return;
    }
    var sql = "select count(id) as countyaoqing from t_user_bind_log where user_dealerid = '{0}'";
    sql = sql.format(userid);
    // console.log(sql);
    query(sql, function(err, rows, fields) {
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows[0]);    
            }
            else{
                callback(null);
            }
        }
    });
}


//获取配置文件
exports.getconfigdata = function(callback){
    callback = callback == null ?nop:callback;
    var sql = "select * from t_configs where name  = 'shenhe' limit 1";
    // console.log(sql);
    query(sql,function(err,rows,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows[0]);    
            }
            else{
                callback(null);
            }
        }
    })
}

//获取自摸活动
exports.get_active_zimo = function(callback){
    callback = callback == null ?nop:callback;
    var nowtime = parseInt(Date.parse(new Date())/1000);
    var sql = "select type,gametype,zimodata,limittimes,moneylimit from t_activity where type  = 6 and status = 1 and (start_time <= '{0}' and end_time >= '{0}') limit 1";
    // console.log(sql);
    sql = sql.format(nowtime);
    query(sql,function(err,rows,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            // console.log("=====dfsdfsdfs");
            // console.log(rows.length);
            if(rows.length > 0){
                //rows[0] = JSON.parse(rows[0]);
                callback(rows[0]);    
            }
            else{
                callback(null);
            }
        }
    })
}


//获取红包活动随机
exports.get_active_on = function(callback){
    callback = callback == null ?nop:callback;
    var nowtime = parseInt(Date.parse(new Date())/1000);
    var sql = "select * from t_activity where (type  = 3 or type = 6) and status = 1 and (start_time <= '{0}' and end_time >= '{0}') limit 1";
    // console.log(sql);
    sql = sql.format(nowtime);
    query(sql,function(err,rows,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
           
            if(rows.length > 0){
                callback(rows[0]);    
            }
            else{
                callback(null);
            }
        }
    })
}


//获取自摸活动
exports.get_zimo_log = function(userid,dayStart,dayEnd,callback){
    callback = callback == null ?nop:callback;
    var sql = "select count(*) as rececount from t_zimoactive_log where userid  = '{0}' and (create_time >= '{1}' and create_time < '{2}') and recestatus = 1";
    // console.log(sql);
    sql = sql.format(userid,dayStart,dayEnd);
    query(sql,function(err,rows,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows[0]);    
            }
            else{
                callback(null);
            }
        }
    })
}


//插入自摸日志表
exports.insert_zimo_log = function(insertData,callback){
    callback = callback == null? nop:callback;
    var nowtime = parseInt(Date.parse(new Date())/1000);
    // console.log("====nowtime")
    // console.log(nowtime)
    if(insertData){
        var sql = "insert into t_zimoactive_log (userid, create_time, gametype, zimovalue, recestatus,receaccount,roomid) values ('{0}', '{1}', '{2}', '{3}',0,'{4}','{5}')";
        sql = sql.format(insertData.userid,nowtime, insertData.gametype,insertData.zimovalue,insertData.receaccount,insertData.roomid);
        // console.log(sql);
        query(sql,function(err,rows,fields){
            if(err){
                if(err.code == 'ER_DUP_ENTRY'){
                    callback(false);
                    return;         
                }
                callback(false);
                throw err;
            }
            else{
                callback(true);
            }
        });
    }
  
}

//活动消息图标
exports.get_hallhuodong_img = function (callback){
    callback = callback == null? nop:callback;
    var sql = "select img,isjump from t_huodong_img where status = 1";
    query(sql, function(err, rows, fields) {
        // console.log(rows);
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows);    
            }
            else{
                callback(null);
            }
        }
    });
}


//获取更新版本
exports.getconfigversion = function(callback){
    callback = callback == null ?nop:callback;
    var sql = "select * from t_configs where name  = 'version' limit 1";
    query(sql,function(err,rows,fields){
        if(err){
            callback(false);
            throw err;
        }
        else{
            if(rows.length > 0){
                callback(rows[0]);    
            }
            else{
                callback(null);
            }
        }
    })
}

exports.query = query;